import Vue from 'vue'
import Component from 'vue-class-component'
import './photoStyle.css'
import FilterViewClass from '@/components/filterView.js'
import FlowListClass from '@/components/flowList.js'
import '../share/shareStyle.css'
import SortViewClass from '@/components/sortView.js'
import register from '../../store/register'
import {PhotoStore} from './store'
import SearchHeadClass from '@/components/searchHeadView.js'
import {formatDate} from '@/utils/commonMethod/method.js'
import BlankPageClass from '@/components/blankPage.js'
import VueScroller from '@/components/VueScroller.vue'

register('photoStore', PhotoStore)

@Component
export default class PhotosClass extends Vue {
  types = ['全部', '明星搭配', '街拍穿搭']
  filterItems = []
  defaultFilterItems = []// 将原始条件保存一份
  sortItems = []
  typeDefault = '全部'
  showTypes = false
  showFiter =false
  showSort = false
  items = []
  word = ''
  wrapperHeight = 0
  isScrollBottom = false
  isCanLoading = true
  currentPage = 1
  sortSelect = {}
  noData = false

  created() {
    this.wrapperHeight = document.documentElement.clientHeight - 161

    this.getFilterItems()
    this.getSortItems()

    let mySelf = this
    eventBus.$on('filterForPhoto', function(val) {
      mySelf.filterChangeStatus()
      mySelf.handleFilterSort()
    })
  }

  updated() {
    // if (this.$route.query.temp) {
    //   if (this.$route.query.temp === 'request') {
    //     this.$route.query.temp = ''
    //     this.filterChangeStatus()
    //     this.currentPage = 1
    //     this.getData()
    //   }
    // }
  }

  handleSearch (value) {
    this.word = value
    this.handleFilterSort()
}

  get caculateHeight() {
    return this.wrapperHeight
  }

  get caculateFlowHeight() {
    return 'height:' + String(this.wrapperHeight) + 'px'
  }

  async getFilterItems () {
    try {
      const response = await this.$axios.post('/picture/v1/pictures/filters', {})
      if (response.status === 0) {
        this.filterItems = response.data
      }
    } catch (e) {
      console.log(e)
    }
  }

  async getSortItems () {
    try {
      const response = await this.$axios.post('/picture/v1/pictures/sorts')
      if (response.status === 0) {
        this.sortItems = response.data
        this.sortSelect = this.sortItems[0]
      }
    } catch (e) {
      console.log(e)
    }
  }

  getParameters() {
    let params = {}
    let selectValue = this.$store.state.photoStore.selectValue
    for (let obj in selectValue) {
      params[obj] = selectValue[obj]
    }
    params['pageIndex'] = this.currentPage
    params['pageSize'] = 10

    params['sortType'] = this.sortSelect.sortType
    params['sortId'] = this.sortSelect.sortId
    params['word'] = this.word
    return params
  }

  findPictures(pageIndex = 1) {
    let params = this.getParameters()
    params['pageIndex'] = pageIndex
    return this.$axios.post('/picture/v1/pictures', params)
      .then(response => {
        if (response.status === 0) {
          if (pageIndex === 1) {
            this.items = []
          }
          return response.data.pictures
        }
      })
  }

  reloadPictures() {
    this.currentPage = 1
    this.$refs.vueScrollerPhoto.$el.scrollTop = 0
    this.getFilterItems()
    this.getSortItems()
    this.findPictures(this.currentPage).then(pictures => {
      console.log('dddddddddddddd', pictures)

      if (pictures) {
        this.items = [...this.items, ...pictures]
      }
      if (!this.items || this.items.length <= 0) {
        this.noData = true
      } else {
        this.noData = false
      }
    }).catch(() => {
      this.noData = true
    })
  }

  infiniteHandler($state) {
    this.findPictures(this.currentPage++).then(pictures => {
      console.log('dddddddddddddd', pictures)
      $state.loaded()
      if (pictures) {
        this.items = [...this.items, ...pictures]
        if (pictures.length < 10) {
          $state.complete()
        }
      } else {
        $state.complete()
      }
      if (!this.items || this.items.length <= 0) {
        this.noData = true
      } else {
        this.noData = false
      }
    }).catch(() => {
      this.noData = true
      $state.complete()
    })
  }

  handleFilterSort() {
    this.$refs.vueScrollerPhoto.refreshHandler()
  }

  // async getData(state) {
  //   if (this.currentPage === 1) {
  //     this.items = []
  //   }
  //   let params = {}
  //   let selectValue = this.$store.state.photoStore.selectValue
  //   for (let obj in selectValue) {
  //     params[obj] = selectValue[obj]
  //   }
  //   params['pageIndex'] = this.currentPage
  //   params['pageSize'] = 10

  //   params['sortType'] = this.sortSelect.sortType
  //   params['sortId'] = this.sortSelect.sortId
  //   params['word'] = this.word
  //   try {
  //     const response = await this.$axios.post('/picture/v1/pictures', params)
  //     if (state) {
  //       state.loaded()
  //     }
  //     if (response.status === 0) {
  //       if (!response.data.pictures || response.data.pictures.length < 10) {
  //         if (state) {
  //           state.complete()
  //         }
  //       }
  //       if (this.currentPage === 1) {
  //         this.items = response.data.pictures
  //       } else {
  //         this.items = this.items.concat(response.data.pictures)
  //       }
  //       this.currentPage ++
  //     }
  //     if (!this.items || this.items.length <= 0) {
  //       this.noData = true
  //     } else {
  //       this.noData = false
  //     }
  //   } catch (e) {
  //     if (state) {
  //       state.complete()
  //     }
  //   }
  // }

  // loadMore (state) {
  //   this.getData(state)
  // }

  // refresh () {
  //   this.currentPage = 1
  //   this.getData()
  // }

  // analyseData (type) {
  //   let leftData = []
  //   let rightData = []
  //   if (!this.items || this.items.length <= 0) {
  //     return []
  //   }
  //   for (var i = 0; i < this.items.length; i++) {
  //     if (i % 2 === 0) {
  //       leftData.push(this.items[i])
  //     } else {
  //       rightData.push(this.items[i])
  //     }
  //   }
  //   if (type === 0) {
  //     return leftData
  //   }
  //   return rightData
  // }

  copyArr(arr) {
    let res = []
    for (let i = 0; i < arr.length; i++) {
      res.push(arr[i])
    }
    return res
  }

   // 点击排序按钮
  handlerShowSortView() {
    this.showFiter = false
    this.sortChangeStatus()
  }

   // 点击排序事件
  handlerSort(index) {
    this.sortSelect = this.sortItems[index]
    this.handleFilterSort()
    setTimeout(() => {
      this.sortChangeStatus()
    }, 300)
  }

  sortChangeStatus () {
    this.showTypes = false
    this.showSort = !this.showSort
    let s = this.$refs.sort
    let f = this.$refs.filter
    if (this.showSort) {
      s.style = 'color:red'
      f.style = 'color:#000'
    } else {
      s.style = 'color:#000'
    }
  }

  // 点击筛选按钮
  handlerShowFilterView() {
    this.showSort = false
    this.filterChangeStatus()
  }

  handlerFilter (index) {
    const value = this.filterItems[index]

    this.$store.dispatch('changeCurrentSuperId', value.key)
    if (value.name === '品牌' && value.children && value.children.length > 0) {
      this.$router.push({name: 'photoBrandList', params: {datas: value.children}})
    } else if (value.children && value.children.length > 0) {
      this.$router.push({name: 'filterTerm', params: {title: value.name, items: value.children, type: 'photo'}})
    }
  }

  handlerClearFilter (items) {
    if (items.children && items.children.length) {
      for (var i = 0; i < items.children.length; i++) {
        let item = items.children[i]
        this.handlerClearFilter(item)
      }
    } else {
      items.checked = false
    }
  }

  handerFilterCancel () {
    this.$store.commit('setSelectFilter', {})
    for (var i = 0; i < this.filterItems.length; i++) {
      let item = this.filterItems[i]
      this.handlerClearFilter(item)
    }
    this.handleClearCache()
    // this.filterChangeStatus()
    // this.currentPage = 0
    // this.getData()
  }

  // 清除store
  handleClearCache() {
    this.$store.dispatch('clearSelect')
  }

  // 确定筛选
  handerFilterSure () {
    this.filterChangeStatus()

    this.handleFilterSort()
  }

  filterChangeStatus () {
    this.showFiter = !this.showFiter
    let f = this.$refs.filter
    let s = this.$refs.sort
    if (this.showFiter) {
      f.style = 'color:red'
      s.style = 'color:#000'
    } else {
      f.style = 'color:#000'
    }
  }

  // 类型
  createTypeItems () {
    if (!this.types || this.types.length <= 0) {
      return
    }
    const item = this.types.map((value, index) => {
      return <div onClick={ (e) => this.handlerClickType(e, index)}>
                <mt-cell style='textAlign:center' title={value} >
                  <icon style='position:absolute;right:15px' v-show={this.typeDefault === value} name='blackPoint' scale = '1.1'/>
                </mt-cell>
             </div>
    })
    return item
  }

  handlerClickType (e, index) {
    e.stopPropagation()
    this.typeDefault = this.types[index]
    setTimeout(() => {
      this.showTypes = !this.showTypes
    }, 200)
  }

  handlerStatus() {
    this.showTypes = !this.showTypes
    this.showFiter = false
  }

  handlerClickItem (value) {
    console.log(value)
    this.$router.push({name: 'photoDetail', params: {photoId: value.pictureId}})
  }

  itemHeight(h) {
    return 'height:' + h + 'px'
  }

  flagString(flagsJson) {
    let arr = JSON.parse(flagsJson)
    let flagString = ''
    if (arr && arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (i === 0) {
          flagString = arr[i]
        } else {
          flagString = flagString + ',' + arr[i]
        }
      }
    }
    return flagString
  }

  // 瀑布流
  // createLeftItems () {
  //   // 瀑布流左边数据
  //   const item = this.analyseData(0).map((value, index) => {
  //     return <div onClick={() => this.handlerClickItem(value)} slot='leftItemName' class="photoColumn">
  //                 <dt><img src={value.cover + '?x-oss-process=image/resize,w_400/quality,q_80'} /></dt>
  //                 <div class='photoColumnInfoClass'>
  //                   <p style='font-size:13px'><span style='font-size:13px' class='textOneLine'>{value.name}</span><font>{formatDate(value.dateAdded)}</font></p>
  //                   <h1 style='font-size:13px'>{this.flagString(value.tags)}</h1>
  //                 </div>
  //               </div>
  //   })
  //   return item
  // }

  // // 瀑布流右边数据
  // createrightItems () {
  //   const item = this.analyseData(1).map((value, index) => {
  //     return <div onClick={() => this.handlerClickItem(value)} slot='rightItemName' class="photoColumn">
  //                  <dt><img src={value.cover + '?x-oss-process=image/resize,w_400/quality,q_80'}/></dt>
  //                 <div class='photoColumnInfoClass'>
  //                   <p style='font-size:13px'><span style='font-size:13px' class='textOneLine'>{value.name}</span><font>{formatDate(value.dateAdded)}</font></p>
  //                   <h1 style='font-size:13px'>{this.flagString(value.tags)}</h1>
  //                 </div>

  //               </div>
  //   })
  //   return item
  // }

  createItems () {
    if (!this.items || this.items.length <= 0) {
      return
    }
    const item = this.items.map((value, index) => {
      return <div onClick={() => this.handlerClickItem(value)} class="photoColumn">
                   <dt><img src={value.cover + '?x-oss-process=image/resize,w_400/quality,q_80'}/></dt>
                  <div class='photoColumnInfoClass'>
                    <p>
                      <span class='textOneLine'>{value.name}</span>
                      <font>{formatDate(value.dateAdded)}</font>
                    </p>
                    <h1 class="textOneLine">{this.flagString(value.tags)}</h1>
                  </div>

                </div>
    })
    return item
  }

  render () {
    return (
      <div class='content'>

        <SearchHeadClass placeholder='搜索图片'
        onValueChange = {value => { this.handleSearch(value) }}>
        </SearchHeadClass>

        <dl class = 'shareStyleClass'>
          <dd ref='sort' onClick={this.handlerShowSortView}>默认排序 <icon style='position:relative;top:2px;left:4px' name = 'paixu' scale = '1.3'/></dd>
          <dd ref='filter' onClick={this.handlerShowFilterView}>筛选<icon style='position:relative;top:2px;left:4px' name = 'shaixuan' scale = '1.5'/></dd>
        </dl>
        <BlankPageClass onRefresh={this.reloadPictures} v-show={this.noData}></BlankPageClass>

        <SortViewClass defaultSort={(this.sortItems && this.sortItems.length > 0) ? this.sortItems[0] : {}} lists={this.sortItems} v-show={this.showSort} onDismiss={this.sortChangeStatus} onClick={index => this.handlerSort(index)} ></SortViewClass>
        <FilterViewClass items={this.filterItems} v-show={this.showFiter} height={this.wrapperHeight} onSure={this.handerFilterSure} onDismiss={this.handerFilterCancel} onClick={this.handlerFilter}></FilterViewClass>

        <VueScroller v-show={!this.noData} ref='vueScrollerPhoto' height={this.wrapperHeight} infinite={this.infiniteHandler} refresh={this.reloadPictures}>
          <div class="photoList">
          {this.createItems()}
          </div>
        </VueScroller>

        </div>
    )
  }
}
